//
//  CJEmoticonKeyboardView.swift
//  SinaWeibo
//
//  Created by 程建 on 16/10/8.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
let emoticonKeyboardHeight: CGFloat = 220
let emoticonToolBarHeight: CGFloat = 37

private let EmoticonCellId = "EmoticonCellId"

class CJEmoticonKeyboardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
       // backgroundColor = UIColor.red
        setupUI()
        
      
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        addSubview(collectionView)
        
        addSubview(toolBar)
        
        addSubview(pageControl)
        
        addSubview(recentLabel)
        
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(emoticonToolBarHeight)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        pageControl.snp.makeConstraints { (make) in
            //pageControl 内容显示默认是居中的
            make.right.left.equalTo(self)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        recentLabel.snp.makeConstraints { (make) in
            make.center.equalTo(pageControl)
        }
        
        
        
        toolBar.emoticonTypeSelectClosure = {type in
            //点击toolBar,让collectionView滚动
            let indexPath = IndexPath(item: 0, section: type.rawValue)
            //为了解决pageControl出现跑马灯效果
            self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
            
            self.updatePageControlData(indexPath: indexPath)
        }
        
        //设置UI界面的时候 就手动调用更新数据的方法
        //主队列异步 实际上还是主队列 当前任务的优先级是比较低优先级 等到主队列空闲的时候 才会执行代码块中的任务
        regsiterNotification()
    }
    
    private func regsiterNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(KsaveRecentEmoticon), object: nil)
        
    }
    
    @objc private func reloadData() {
        //刷新第0组
        //如果当前显示的是第0组,就不执行刷新
        let indexPath = collectionView.indexPathsForVisibleItems.last!
        if indexPath.section != 0 {
            collectionView.reloadItems(at: [IndexPath(item: 0, section: 0)])
        }
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.updatePageControlData(indexPath: IndexPath(item: 0, section: 0))
    }
    
    /// 根据indexPath 更新pageControl的显示数据
    ///
    /// - parameter indexPath: 索引对象
    func updatePageControlData(indexPath: IndexPath) {
        
        //1. 根据indexPath.section  --> 获取到allEmoticons对应的二维数组
        let pageEmoticons = CJEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section]
        //2.设置pageControl的数据
        pageControl.numberOfPages = pageEmoticons.count
        pageControl.currentPage = indexPath.item
        //3.设置最近文本的显示和pageControl的显示
        pageControl.isHidden = indexPath.section == 0
        recentLabel.isHidden = indexPath.section != 0
        
    }
    

    //懒加载子控件
     lazy var collectionView:UICollectionView = {
    
        let layout = UICollectionViewFlowLayout()
        //设置滚动方向
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: ScreenWidth, height: emoticonKeyboardHeight - emoticonToolBarHeight)
        //设置行间距
        layout.minimumLineSpacing = 0
        
        let collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        
        //注册cell
        collection.register(CJEmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
        //实现数据源方法
        //设置数据源代理
        collection.dataSource = self
        collection.delegate = self
        //设置分页效果
        collection.isPagingEnabled = true
        //设置弹簧
        collection.bounces = false
        return collection
    }()
    
    //底部工具条
     lazy var toolBar: CJEmoticonToolBar = CJEmoticonToolBar()
    
    //
    lazy var pageControl: UIPageControl = {
        let page = UIPageControl()
        page.numberOfPages = 5
        page.currentPage = 2
        //OC项目运行环境下LLDB看的
        page.setValue(#imageLiteral(resourceName: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        page.setValue(#imageLiteral(resourceName: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        return page
    }()
    
    
    //最近提示文字
    private lazy var recentLabel: UILabel = UILabel(title: "最近使用的表情", textColor: UIColor.orange, fontSize: 10)
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension CJEmoticonKeyboardView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        let sectionEmoticon = CJEmoticonTools.sharedEmoticonTools.allEmoticons.count
        return sectionEmoticon
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let sectionEmoticon = CJEmoticonTools.sharedEmoticonTools.allEmoticons
        return sectionEmoticon[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCellId, for: indexPath) as! CJEmoticonCell

        cell.backgroundColor = UIColor.white
        
        cell.indexPath = indexPath
        
        let emoticons = CJEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section][indexPath.item]

        print(emoticons)
        
        cell.emoticons = emoticons
        
        return cell
    }
    
    
    //实现代理方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let contentOffsetx = scrollView.contentOffset.x + 0.5 * ScreenWidth
        let point = CGPoint(x: contentOffsetx, y: 1)
        //根据一个点确定indexPath
        let indexPath = collectionView.indexPathForItem(at:point)
        //让toolBar去更新选中的按钮
        self.toolBar.setEmoticonTypeSelected(indexPath: indexPath!)
        //更新pageControl的数据
        self.updatePageControlData(indexPath: indexPath!)
    }
    
}

